﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using WorkFlowCore.Host.ViewModels;

namespace WorkFlowCore.Host.Controllers.Filters
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionContext> logger;

        public ExceptionFilter(ILogger<ExceptionContext> logger)
        {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            context.Result = new JsonResult(OutputDto.Failed<string>($"异常：{context.Exception.Message}"));
            logger.LogError($"异常：{context.Exception.Message}", context.Exception);
            context.HttpContext.Response.StatusCode = 500;
            Console.Error.WriteLine(context.Exception.ToString());
            context.ExceptionHandled = true;
        }
    }
}
